package cn.avalon.user.service.impl;


import cn.avalon.basic.exception.BusinessException;
import cn.avalon.basic.service.impl.BaseServiceImpl;
import cn.avalon.basic.utils.Md5Utils;
import cn.avalon.basic.utils.StrUtils;
import cn.avalon.user.domain.Logininfo;
import cn.avalon.user.domain.User;
import cn.avalon.user.dto.UserDto;
import cn.avalon.user.mapper.LogininfoMapper;
import cn.avalon.user.mapper.UserMapper;
import cn.avalon.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void phoneRegister(UserDto userDto) {

        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String repwd = userDto.getRepwd();

        // 1.检验：空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(repwd)) {
            throw new BusinessException("信息不能为空");
        }
        System.out.println(pwd);
        System.out.println(repwd);
        // 2.校验：密码是否相同
        if (!pwd.equals(repwd)) {
            throw new BusinessException("两次密码不一致");
        }

        // 3.校验：短信验证码是否过期是否正确
        Object codeObj = redisTemplate.opsForValue().get("register:" + phone);
        if (codeObj == null) {
            throw new BusinessException("手机验证码已过期，请重新获取");
        }
        if (!codeObj.toString().split(":")[0].equals(phoneCode)) {
            throw new BusinessException("验证码错误，请重新输入");
        }

        // 4.添加到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        // 先添加logininfo获取自增id
        logininfoMapper.save(logininfo);
        // 再添加user
        user.setLogininfo_id(logininfo.getId());
        userMapper.save(user);
    }

    @Override
    @Transactional
    public void registerEmail(UserDto userDto) throws MessagingException {
        // 1.空值校验
        if (StringUtils.isEmpty(userDto.getEmail()) || StringUtils.isEmpty(userDto.getPwd()) || StringUtils.isEmpty(userDto.getRepwd())) {
            throw new BusinessException("请输入正确的邮箱和密码");
        }
        // 2.判断邮箱是否已注册
        User email = userMapper.findByEmail(userDto.getEmail());
        if (email != null) {
            throw new BusinessException("邮箱已存在，请直接登录");
        }
        // 3.判断两次密码是否一致
        if (!userDto.getPwd().equals(userDto.getRepwd())) {
            throw new BusinessException("两次密码不一致");
        }
        // 4.保存用户信息 先保存t_logininfo
        // 这里逻辑有问题，要写email的方法来保存
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setDisable(false);
        logininfoMapper.save(logininfo);
        // 在保存t_user
        user.setLogininfo_id(logininfo.getId());
        user.setState(0);
        userMapper.save(user);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("709785494@qq.com");
        helper.setSubject("邮箱账号激活");
        helper.setText("请点击下面链接激活账号\r\n<a href='http://localhost:8080/user/register/email/activate/"+user.getId()+"'>激活账号</a>",true);
        helper.setTo(userDto.getEmail());
        javaMailSender.send(mimeMessage);
    }

    @Override
    @Transactional
    public void emailActivate(Long id) {
        User user = userMapper.findById(id);
        user.setState(1);
        userMapper.update(user);
        Logininfo logininfo = logininfoMapper.findById(user.getId());
        logininfo.setDisable(true);
        logininfoMapper.update(logininfo);
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        if (!StringUtils.isEmpty(userDto.getEmail())){
            user.setUsername(userDto.getEmail());
            user.setEmail(userDto.getEmail());
        } else {
            user.setUsername(userDto.getPhone());
            user.setPhone(userDto.getPhone());
        }
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        // 按照属性同名原则
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    @Override
    @Transactional
    public void save(User user) {
        // 处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        // 保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);

        // 保存user
        user.setLogininfo_id(logininfo.getId());
        super.save(user);
    }

    @Override
    @Transactional
    public void remove(Long id) {
        // 删除登录信息logininfo
        User user = userMapper.findById(id);
        logininfoMapper.remove(user.getLogininfo_id());

        // 删除user信息
        userMapper.remove(id);
    }

    @Override
    @Transactional
    public void update(User user) {//网上传递的user时没有loggininfo_id
        // 处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        super.update(user);

        // 获取登录信息id
        Long logininfo_id = userMapper.findById(user.getId()).getLogininfo_id();

        // 创建logininfo
        Logininfo logininfo = logininfoMapper.findById(logininfo_id);//id,type ,state
        // 将新的数据覆盖旧的数据
        BeanUtils.copyProperties(user,logininfo); // 5个数据新的 - 用户名，邮箱，电话，盐值，密码
        // 重置logininfo_id
        logininfo.setId(logininfo_id);
        logininfoMapper.update(logininfo);
    }
}
